<template>
  <div style="background-color: #fff; height: 100%; overflow-x: auto">
    <div style="display: flex; justify-content: space-between">
      <a-form size="small" :model="pageData" layout="inline" style="margin-top: 20px">
        <a-form-item label="工段">
          <a-select style="width: 200px" class="bacClass" @search="sectionSearch()" @change="processSearch()"
            v-model="pageData.sectionName" allow-search allow-clear>
            <a-option v-for="item in pageData.sectionNameList" :value="item.sectionName" :key="item">
              {{ item.sectionName }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="工序">
          <a-select style="width: 200px" class="bacClass" @search="processSearch()" v-model="pageData.processId"
            allow-search allow-clear>
            <a-option v-for="item in pageData.processList" :value="item.id" :key="item">
              {{ item.processName }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="流转卡号">
          <a-input class="bacClass" style="width: 200px" v-model="pageData.flowCardCode" allow-clear></a-input>
        </a-form-item>
        <a-form-item label="处理状态">
          <a-select v-model="pageData.handleStatus" style="width: 200px" allow-clear class="bacClass">
            <a-option v-for="item in pageData.statusList" :key="item.code" :label="item.name" :value="item.name" />
          </a-select>
        </a-form-item>
      </a-form>
      <Toolbar style="margin-top: 20px" :items="['查询', '处理']" @select="selectHandle" @handle="handling">
      </Toolbar>
    </div>
    <div class="cssTable">
      <a-spin :loading="pageData.pageLoading" tip="加载中" dot style="height: 100%; width: 100%; z-index: 999">
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" style="height: 74vh"
          :suppressDragLeaveHidesColumns="true" rowSelection="multiple" @grid-ready="gridReady"
          :defaultColDef="defaultColDef" class="ag-theme-alpine" :rowData="pageData.tableList"
          :columnDefs="tableColumns" :localeText="localeText1">
        </AgGridVuesCopys>
      </a-spin>
    </div>
    <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
      @change="PageSize" @page-size-change="change1" style="justify-content: center; margin-top: 12px" :page-size="size"
      :current="page" />
  </div>
  <a-drawer style="z-index: 999" ok-text="保存" cancel-text="关闭" :drawer-style="{ zIndex: 9999 }" :mask-closable="false"
    :width="400" :visible="pageData.showAdd" unmountOnClose height="100%" @ok="sideOk"
    @cancel="pageData.showAdd = false">
    <template #title>{{ pageData.sideTitle }}</template>
    <div>
      <a-form ref="formRef" :model="dataForm" layout="horizontal">
        <a-form-item label="处理状态" label-col-flex="80px" field="handleStatusCode" :validate-trigger="['change', 'blur']"
          :rules="[{ required: true, message: '处理状态必填' }]">
          <el-select v-model="dataForm.handleStatusCode" filterable clearable :collapse-tags-tooltip="true"
            class="bacClass" style="width: 100%">
            <el-option v-for="item in pageData.statusList" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </a-form-item>
        <a-form-item label="处理意见" label-col-flex="80px" field="handlingOpinion" :validate-trigger="['change', 'blur']"
          :rules="[{ required: true, message: '处理意见必填' }]">
          <a-input class="bacClass" v-model="dataForm.handlingOpinion" allow-clear></a-input>
        </a-form-item>
        <a-form-item label="承接单位" label-col-flex="80px">
          <a-input class="bacClass" v-model="dataForm.nextHandleDept" allow-clear disabled></a-input>
        </a-form-item>
        <a-form-item label="承接人" label-col-flex="80px">
          <el-select v-model="dataForm.nextHandlerCode" filterable clearable :collapse-tags-tooltip="true"
            class="bacClass" @change="handlerChange(1)" style="width: 100%">
            <el-option v-for="item in pageData.handlerList" :key="item.code" :label="item.code + '/' + item.name"
              :value="item.code" />
          </el-select>
        </a-form-item>
        <a-form-item label="责任单位" label-col-flex="80px">
          <a-input class="bacClass" v-model="dataForm.dutyDept" disabled></a-input>
        </a-form-item>
        <a-form-item label="责任人" label-col-flex="80px">
          <el-select v-model="dataForm.dutyEmployeeCode" filterable clearable placeholder=" "
            :collapse-tags-tooltip="true" class="bacClass" @change="handlerChange(2)" style="width: 100%">
            <el-option v-for="item in pageData.handlerList" :key="item.code" :label="item.code + '/' + item.name"
              :value="item.code" />
          </el-select>
        </a-form-item>
      </a-form>
    </div>
  </a-drawer>
</template>

<script lang='ts' setup>
import { reactive, toRefs, ref, onMounted } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { Search, CirclePlus, Delete, EditPen } from '@element-plus/icons-vue'

const pagingList1: any = ref(pagingList)
const localeText1: any = ref(localeText)
const pageData: any = reactive({
  showAdd: false,
  sideTitle: '',
  rHeight: 0,
  tableList: [],
  pageLoading: false,
  flowCardCode: '',
  companyId: null,
  sectionName: '',
  processId: null,
  handlerList: [],
  handler: '',
  handlerCode: '',
  statusList: [],
  handleStatus: '',
})

const dataForm: any = reactive({
  defectId: null,
  handleStatusCode: '',
  handleStatus: '',
  nextHandleDept: '',
  nextHandlerCode: '',
  nextHandler: '',
  dutyDept: '',
  dutyEmployeeCode: '',
  dutyPerson: '',
})

const defaultColDef: any = {
  sortable: true,
  resizable: true,
  filter: true,
}

//未处理
const gridOption = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
}
const tableColumns: any = [
  {
    headerName: '',
    checkboxSelection: true,
    headerCheckboxSelection: true,
    pinned: 'left',
    width: 50,
  },
  { headerName: '异常单号', field: 'exceptionCode', width: 150 },
  { headerName: '流转卡号', field: 'flowCardCode', width: 150 },
  { headerName: '工段', field: 'sectionName', width: 150 },
  { headerName: '工序', field: 'processName', width: 150 },
  { headerName: '客户', field: 'customName', width: 150 },
  { headerName: '色号', field: 'colorCode', width: 150 },
  { headerName: '色称', field: 'colorName', width: 150 },
  { headerName: '布号', field: 'clothCode', width: 150 },
  { headerName: '匹数', field: 'houseNum', width: 150 },
  // { headerName: '磅数', field: 'createTime', width: 150 },
  // { headerName: '宽幅', field: 'createTime', width: 150 },
  //   { headerName: '克重', field: 'flowCardWeight', width: 150 },
  // { headerName: '缩水W', field: 'createTime', width: 150 },
  // { headerName: '缩水L', field: 'createTime', width: 150 },
  { headerName: '问题类型', field: 'exceptionType', width: 150 },
  { headerName: '问题描述', field: 'exceptionDesc', width: 150 },
  { headerName: '不合格数量', field: 'unqualifiedNum', width: 150 },
  { headerName: '备注', field: 'remark', width: 150 },
  { headerName: '提出单位', field: 'applyDept', width: 150 },
  { headerName: '提出人', field: 'applyEmployee', width: 150 },
  { headerName: '提出时间', field: 'createTime', width: 150 },
  { headerName: '处理人', field: 'handler', width: 150 },
  { headerName: '处理意见', field: 'resolution', width: 150 },
  { headerName: '责任单位', field: 'dutyDept', width: 150 },
  { headerName: '责任人', field: 'dutyPerson', width: 150 },
  { headerName: '承接单位', field: 'nextHandlerDept', width: 150 },
  { headerName: '承接人', field: 'nextHandler', width: 150 },
  { headerName: '处理状态', field: 'handleStatus', pinned: 'right', width: 150 },
  {
    headerName: '操作',
    field: 'action',
    width: 146,
    pinned: 'right',
    cellRenderer: {
      template: `<a-tag class="tagCss" v-if="f" @click="c">修改</a-tag>
                 <a-tag class="tagCss" v-else disabled style="color:#d1d1d1 !important">修改</a-tag>`,
      setup(props: any) {
        const c = () => {
          editHandler(props.params.data)
        }
        return {
          c,
          f: pageData.handlerCode == props.params.data.handlerCode,
        }
      },
    },
  },
]

//分页
const total = ref(0)
const page = ref(1)
const size = ref(10)
function PageSize(val: any) {
  page.value = val
  doRefresh()
}
function change1(val: any) {
  size.value = val
  doRefresh()
}

//查询
const formRef = ref()
const doRefresh = () => {
  pageData.pageLoading = true
  post({
    url: '/aps/dwDefect/findPagedDefectsByCondition',
    data: {
      flowCardCode: pageData.flowCardCode,
      sectionName: pageData.sectionName,
      processId: pageData.processId,
      handleStatus: pageData.handleStatus,
      current: page.value,
      size: size.value,
    },
  })
    .then(({ data, code }: any) => {
      if (code === 200) {
        pageData.tableList = data.records
        gridOption.value.setRowData(data.records)
        total.value = data.total
      }
    })
    .catch(console.log)
    .finally(() => {
      pageData.pageLoading = false
    })
}

const selectHandle = () => {
  page.value = 1
  doRefresh()
}

const handling = () => {
  if (gridOption.value.getSelectedRows().length === 0) {
    Message.warning('请勾选数据！')
    return
  }
  if (gridOption.value.getSelectedRows().length > 1) {
    Message.warning('只能勾选一条数据！')
    return
  }
  if (gridOption.value.getSelectedRows()[0].nextHandlerCode != pageData.handlerCode) {
    Message.warning('当前账号无权限处理！')
    return
  }
  for (let key in dataForm) {
    dataForm[key] = ''
  }
  dataForm.defectId = gridOption.value.getSelectedRows()[0].defectId
  pageData.sideTitle = '处理'
  pageData.showAdd = true
}

const editHandler = (record: any) => {
  pageData.pageLoading = true
  get({
    url: '/aps/dwDefectResolution/findDefectResolutionById?id=' + record.resolutionId,
  }).then(({ code, data, message }) => {
    if (code == 200) {
      for (let key in data) {
        dataForm[key] = data[key]
      }
      pageData.showAdd = true
      pageData.sideTitle = '修改'
      pageData.pageLoading = false
    } else {
      Message.error(message)
      pageData.pageLoading = false
    }
  })
}

const sideOk = () => {
  formRef.value?.validate().then((err: any) => {
    if (!err) {
      pageData.pageLoading = true
      dataForm.handleStatus = pageData.statusList.find((o: any) => o.code == dataForm.handleStatusCode).name
      post({
        url: '/aps/dwDefectResolution/insertOrUpdateDefectResolution',
        data: {
          ...dataForm,
          handlerCode: pageData.handlerCode,
          handler: pageData.handler,
        },
      }).then(({ code, message }) => {
        if (code == 200) {
          Message.success('成功')
          pageData.showAdd = false
          pageData.pageLoading = false
          doRefresh()
        } else {
          Message.error(message)
        }
      })
    }
  })
}

//承接人 责任人
const getHandler = (val: any) => {
  post({
    url: 'org/hrEmployee/getList',
    data: {
      deleteState: 0,
      obsoleteState: 0,
      company_id: pageData.companyId,
      department_id: '',
      ygText: val,
    },
  }).then(({ data, code }: any) => {
    if (code === 200) {
      pageData.handlerList = data
    } else {
      Message.error({
        content: '该部门无员工信息！',
        duration: 5000,
      })
    }
  })
}

const handlerChange = (num: any) => {
  if (num == 1) {
    dataForm.nextHandleDept = ''
    dataForm.nextHandler = ''
    let data = pageData.handlerList.find((o: any) => dataForm.nextHandlerCode === o.code)
    dataForm.nextHandleDept = data.departmentName
    dataForm.nextHandler = data.name
  } else {
    dataForm.dutyDept = ''
    dataForm.dutyPerson = ''
    let data = pageData.handlerList.find((o: any) => dataForm.dutyEmployeeCode === o.code)
    dataForm.dutyDept = data.departmentName
    dataForm.dutyPerson = data.name
  }
}

//获取当前登录账号
const getUserToken = () => {
  post({
    url: 'admin/acl/user/findUserToken',
  }).then((res: any) => {
    if (res.code === 200) {
      pageData.companyId = res.data.data.firmId
      pageData.handlerCode = res.data.data.empMap.code
      pageData.handler = res.data.data.empMap.name
    }
  })
}

//工段下拉
const sectionSearch = () => {
  post({
    url: '/pdm/worksection/getFieldValue',
    data: {
      sectionName: pageData.sectionName,
    },
  }).then(({ data, code, message }: any) => {
    if (code === 200) {
      pageData.sectionNameList = data
    } else {
      Message.error(message)
    }
  })
}

//工序下拉
const processSearch = () => {
  pageData.processId = ''
  pageData.processList = []
  if (pageData.sectionName) {
    post({
      url: 'pdm/worksectionWorkprocedure/selectPage',
      data: {
        deleteState: 0,
        size: 10000,
        page: 1,
        sectionName: pageData.sectionName,
      },
    }).then(({ data, code }: any) => {
      if (code === 200) {
        pageData.processList = data.list
      }
    })
  }
}

//处理状态下拉
const statusSearch = () => {
  post({
    url: '/aps/dwDefectStatus/findPagedStatus',
    data: {
      current: 1,
      size: 10000,
    },
  })
    .then(({ data, code, message }: any) => {
      if (code === 200) {
        pageData.statusList = data.records
      } else {
        Message.error(message)
      }
    })
}

onMounted(() => {
  pageData.rHeight = document.getElementsByClassName('main-section')[0]?.clientHeight
  //弹出层的高
  if (pageData.rHeight !== undefined) {
    pageData.rHeight = pageData.rHeight
  }
  getUserToken()
  getHandler('')
  sectionSearch()
  statusSearch()
  doRefresh()
})
</script>
<style lang='less' scoped>
.main-container {
  height: 100%;
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

:deep(.el-input__wrapper) {
  padding: 0;
  box-shadow: 0 0 0 0;
  border-radius: 0;
  height: 28px;
}

:deep(.el-select) {
  --el-select-input-focus-border-color: white;
  --el-select-border-color-hover: white;
}
</style>